package Model.InboxMessages;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;

import DBAccess.DBAccess;
import Model.User;

/**
 * Servlet implementation class MessageServlet
 */
@WebServlet("/sendmsg")
public class MessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MessageServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	int msgID = Integer.parseInt(request.getParameter("msgID"));
    	
		
		Message myMsg = Inbox.viewMessage(msgID);
		JSONObject result = new JSONObject(myMsg);
		response.getWriter().print(result.toString());
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String to = request.getParameter("to");
		String msg = request.getParameter("message");
		HttpSession session = request.getSession();
		if(to !=""){
			
			int fromId = Integer.parseInt(session.getAttribute("userID").toString());
			int toId = User.getId(request.getParameter("to"));
			Message.sendMessage(fromId, toId, msg);
			
			RequestDispatcher dispatcher = 
	    			request.getRequestDispatcher("/inbox.jsp"); 
	    	if (dispatcher != null) 
	    		dispatcher.forward(request, response);
		}else{

		}
	}
		

}
